//
//  YJHBViewController.m
//  Estate
//
//  Created by kevin on 16/9/5.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define margin 15

#import "YJHBViewController.h"
#import "DefaineCell.h"
#import "DoubleLabCell.h"
#import "B_wuLiaoCell.h"
#import "LeaderYijianCell.h"
#import "explainTableViewCell.h"
#import "ZJRWViewController.h"
#import "addDiaryHeadView.h"
#import "InspectTotalRecordModel.h"


@interface YJHBViewController ()

// 一键汇总模型
@property (strong, nonatomic) InspectTotalRecordModel *itrModel;

// 数据源
@property (strong, nonatomic) NSMutableArray *dataArr;

@end


@implementation YJHBViewController

// 数据源
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"一键汇总";

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DoubleLabCell" bundle:nil] forCellReuseIdentifier:@"dCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"sCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LeaderYijianCell" bundle:nil] forCellReuseIdentifier:@"detailss"];
    [self.tableView registerNib:[UINib nibWithNibName:@"explainTableViewCell" bundle:nil] forCellReuseIdentifier:@"explainCell"];
    
    // 获取汇总表数据
    [self getInspectTotalRecord];
    // 获取数据源
    [self getDataSource];
    // 刷新巡检列表状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateInspector) name:@"AKeyCombination" object:nil];
}

// 刷新数据
- (void)updateInspector {
    [self.dataArr removeAllObjects];
    [self getDataSource];
    [self.tableView reloadData];
}

// 获取汇总表数据
- (void)getInspectTotalRecord {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *ITRSql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_TOTAL_RECORD WHERE INSPECT_PROCESS_ID = '%@'", self.inspectProcessDic[@"INSPECT_PROCES_ID"]];
    FMResultSet *ITRResult = [db executeQuery:ITRSql];
    
    while ([ITRResult next]) {
        NSDictionary *dic=[ITRResult resultDictionary];
        InspectTotalRecordModel *itrModel = [InspectTotalRecordModel yy_modelWithDictionary:dic];
        self.itrModel = itrModel;
    }
    [db close];
}

// 获取数据源
- (void)getDataSource {
    [self.dataArr removeAllObjects];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    if (self.itrModel.INSPECT_TOTAL_INFO) {
        // 一键合并的巡检项(汇总信息)
        NSData *totalInfoData = [self.itrModel.INSPECT_TOTAL_INFO dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *totalInfoArr = [LSUtility toArrayOrNSMutableDictionary:totalInfoData];
        
        // 查找所有的一级巡检项ID
        NSArray *firstUserIDArr = [self getInspectItem];
        for (int i = 0; i < firstUserIDArr.count; i++) {
            NSDictionary *firstdic = firstUserIDArr[i];
            
            NSMutableArray *noNullArr = [NSMutableArray array];
            for (int j = 0; j < totalInfoArr.count; j++) {
                NSDictionary *totalInfoDic = totalInfoArr[j];
                
                // 巡检项不为空
                if (![totalInfoDic[@"inspectItemId"] isEqualToString:@""]) {
                    
                    NSString *iiSql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE ID = '%@' AND PARENT_ID = '%@'", totalInfoDic[@"inspectItemId"], firstdic[@"ID"]];
                    FMResultSet *iiResult = [db executeQuery:iiSql];
                    
                    while ([iiResult next]) {
                        NSDictionary *dic2 = @{@"ITEM_ID":totalInfoDic[@"inspectItemId"], @"RESULT":DEFISNUL(totalInfoDic[@"inspectResult"]), @"USER_ID":totalInfoDic[@"inspectUserId"], @"USER_ITEM_ID":totalInfoDic[@"userItemId"], @"NAME2":totalInfoDic[@"inspectItemInfo"]};
                        [noNullArr addObject:dic2];
                    }
                    
                    // 数据为一级巡检项
                    if ([totalInfoDic[@"inspectItemId"] isEqualToString:firstdic[@"ID"]]) {
                        NSDictionary *dic2 = @{@"ITEM_ID":totalInfoDic[@"inspectItemId"], @"RESULT":totalInfoDic[@"inspectResult"], @"USER_ID":totalInfoDic[@"inspectUserId"], @"USER_ITEM_ID":totalInfoDic[@"userItemId"], @"NAME2":totalInfoDic[@"inspectItemInfo"]};
                            [noNullArr addObject:dic2];
                    }
                }
            }
            
            if (noNullArr.count > 0) {
                NSDictionary *dic1 = @{@"NAME1":firstdic[@"NAME"], @"ARRAY":noNullArr};
                [self.dataArr addObject:dic1];
            }
        }
        
        // 巡检项为空
        NSMutableArray *nullArr = [NSMutableArray array];
        for (int i = 0; i < totalInfoArr.count; i++) {
            NSDictionary *totalInfoDic = totalInfoArr[i];
            
            if ([totalInfoDic[@"inspectItemId"] isEqualToString:@""]) {
                NSDictionary *dic2 = @{@"ITEM_ID":totalInfoDic[@"inspectItemId"], @"RESULT":DEFISNUL(totalInfoDic[@"inspectResult"]), @"USER_ID":totalInfoDic[@"inspectUserId"], @"USER_ITEM_ID":totalInfoDic[@"userItemId"], @"NAME2":totalInfoDic[@"inspectItemInfo"]};
                [nullArr addObject:dic2];
            }
        }
        if (nullArr.count > 0) {
            NSDictionary *dic1 = @{@"NAME1":@"其他", @"ARRAY":nullArr};
            [self.dataArr addObject:dic1];
        }
    }
    [db close];
}

// 查找所有的一级巡检项ID
- (NSArray *)getInspectItem {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];

    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE PARENT_ID = '0'"];
    FMResultSet *result = [db executeQuery:sql];

    // ID数组
    NSMutableArray *IDArr = [NSMutableArray array];
    while ([result next]) {
        NSString *ID = [result stringForColumn:@"ID"];
        NSString *name = [result stringForColumn:@"INSPECT_NAME"];

        NSDictionary *dic = @{@"ID":ID, @"NAME":name};
        [IDArr addObject:dic];
    }
    [db close];
    return IDArr;
}


#pragma  mrak--UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count + 2;
}

// 组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.001;

    } else {
        return 25;
    }
}

// 组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSDictionary *dic;
    if (section != (self.dataArr.count + 1) && section != 0) {
        dic = self.dataArr[section - 1];
    }
    
    if (section == (self.dataArr.count + 1)) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        view.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        
        UIImageView *imageViewS = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        imageViewS.image = [UIImage imageNamed:@"juchishang"];
        UIImageView *imageViewX = [[UIImageView alloc]initWithFrame:CGRectMake(0, 17, DEF_SCREEN_WIDTH, 8)];
        imageViewX.image = [UIImage imageNamed:@"juchixia"];
        
        [view addSubview:imageViewS];
        [view addSubview:imageViewX];
        return view;
        
    } else if (section == 0) {
        return nil;
        
    } else if (section == 1) {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        view.backgroundColor=[UIColor whiteColor];
        
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, DEF_SCREEN_WIDTH, 15)];
        titleLab.font = [UIFont systemFontOfSize:17.];
        titleLab.textColor = [UIColor colorWithRed:0.47 green:0.48 blue:0.49 alpha:1.00];
        titleLab.text = dic[@"NAME1"];
        [view addSubview:titleLab];
        return view;

    } else {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        view.backgroundColor=[UIColor whiteColor];
        
        //横线
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 5)];
        line.backgroundColor=[UIColor colorWithRed:0.89 green:0.89 blue:0.90 alpha:1.00];
        [view addSubview:line];
        
        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(8, 13, DEF_SCREEN_WIDTH, 15)];
        titleLab.font = [UIFont systemFontOfSize:17.];
        titleLab.textColor = [UIColor colorWithRed:0.47 green:0.48 blue:0.49 alpha:1.00];
        titleLab.text = dic[@"NAME1"];
        [view addSubview:titleLab];
        return view;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 25;
        
    } else if (section == (self.dataArr.count + 1)) {
        return 40;
        
    } else {
        return 0.001;
    }
}

// 组尾
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    // 第一组
    if (section == 0) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        view.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        
        UIImageView *imageViewS = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        imageViewS.image = [UIImage imageNamed:@"juchishang"];
        UIImageView *imageViewX = [[UIImageView alloc]initWithFrame:CGRectMake(0, 17, DEF_SCREEN_WIDTH, 8)];
        imageViewX.image = [UIImage imageNamed:@"juchixia"];
        
        [view addSubview:imageViewS];
        [view addSubview:imageViewX];
        return view;
        
    } else if (section == (self.dataArr.count + 1)) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
        view.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        
        UIImageView *imageViewS = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        imageViewS.image = [UIImage imageNamed:@"juchishang"];
        [view addSubview:imageViewS];
        return view;
        
    } else {
        return nil;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSDictionary *firstDic;
    if (section != (self.dataArr.count + 1) && section != 0) {
        firstDic = self.dataArr[section - 1];
    }
    NSArray *arr = firstDic[@"ARRAY"];
    
    if(section == 0) {
        return 4;
    }else if (section == (self.dataArr.count + 1)) {
        return 1;
    } else {
        return arr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {    
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    NSDictionary *firstDic;
    if (section != (self.dataArr.count + 1) && section != 0) {
        firstDic = self.dataArr[section - 1];
    }
    NSArray *arr = firstDic[@"ARRAY"];
    NSDictionary *secondDic = arr[row];
    
    //第一组
    if(section==0) {
        if(row==0) {
            DoubleLabCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dCell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor colorWithRed:0.85 green:0.93 blue:0.97 alpha:1.00];
            
            // 标题
            NSString *title=[NSString stringWithFormat:@">>%@", self.inspectProcessDic[@"SECOND_TITLE"]];
            cell.title.text = title;
            cell.title.textColor = [UIColor colorWithRed:0.24 green:0.64 blue:0.61 alpha:1.00];
            
            // 状态
            cell.detail.text = @"";
            return cell;
            
        } else {
            if(row==1) {
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"项      目:";
                dCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
                return dCell;

            } else if (row == 2) {
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"记 录 人:";
                dCell.text.text = [LSUtility getuserIdByUserName:self.itrModel.INSPECT_TOTAL_USER][@"REAL_NAME"];;
                return dCell;
                
            } else {
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"时      间:";
                dCell.text.text = self.itrModel.CREATE_TIME;
                return dCell;
                
            }
        }
    } else if (section == self.dataArr.count + 1) {
        explainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"explainCell" forIndexPath:indexPath];
        cell.isEdit = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.title.text = @"说     明:";
        cell.text.text = self.itrModel.INSPECT_TOTAL_DESC;
        cell.text.placeholder = @"请填写检查内容";
        return cell;
        
    } else {
        // 查找巡检项名称
//        NSString *itemName = [self getInspectItemNameByItemID:secondDic[@"ITEM_ID"]];
        
        // 查找本条巡检项的状态
        NSString *state = [self getInspectItemStateByUserItemID:secondDic[@"USER_ITEM_ID"]];
        // 查找本条巡检项状态为3的条数
        int count = [LSUtility getInspectItemCountByUserItemID:secondDic[@"USER_ITEM_ID"] withState:@"3"];
        LeaderYijianCell *cell = [LeaderYijianCell cellWithTableView:tableView];
        cell.titleField.userInteractionEnabled = NO;
        
        // 背景状态
        if ([secondDic[@"RESULT"] isEqual:@"0"]) {
            cell.titleField.backgroundColor = [UIColor colorWithRGBHex:0xFFEFEF];
            if ([state isEqualToString:@"3"] && count > 1) {
                cell.stateImage.image = [UIImage imageNamed:@"butongguo"];
            } else if ([state isEqualToString:@"4"]) {
                cell.stateImage.image = [UIImage imageNamed:@"zhenggai_state"];
            } else if ([state isEqualToString:@"5"]) {
                cell.stateImage.image = [UIImage imageNamed:@"tongguo"];
            } else {
                UIImage *image = [LSUtility createImageWithColor:[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00]];
                cell.stateImage.image = image;
            }
        } else {
            cell.titleField.backgroundColor = [UIColor colorWithRGBHex:0xE7EEF4];
            cell.stateImage.image = [UIImage imageNamed:@"tongguo"];
        }
        
        // 隐藏删除按钮
        cell.deleteBtn.hidden = YES;
        cell.leftConstraint.constant = -25. * BIZ;
        cell.name.text = [LSUtility getuserIdByUserName:secondDic[@"USER_ID"]][@"REAL_NAME"];
        cell.titleField.text = secondDic[@"NAME2"];
        
        // 详情信息
        cell.detailBlick = ^ {
            NSLog(@"用户巡检项id：%@",secondDic[@"USER_ITEM_ID"]);
            ZJRWViewController *zjCtr = [[ZJRWViewController alloc]init];
            zjCtr.IPID = self.inspectProcessDic[@"INSPECT_PROCES_ID"];
            zjCtr.IUIID = secondDic[@"USER_ITEM_ID"];
            zjCtr.firstInspectItem = firstDic[@"NAME1"];
            zjCtr.secondInspectItem = secondDic[@"NAME2"];
            [self.navigationController pushViewController:zjCtr animated:YES];
        };
        return cell;
    }
}

// 查找巡检项名称
- (NSString *)getInspectItemNameByItemID:(NSString *)itemID {
    // 查找二级巡检项名称
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 巡检项名称
    NSString *itemName;
    if (![itemID isEqualToString:@""]) {     // 巡检项ID存在
        NSString *iiSql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_ITEM WHERE ID = '%@'", itemID];
        FMResultSet *iiResult = [db executeQuery:iiSql];
        while ([iiResult next]) {
            itemName = [iiResult stringForColumn:@"INSPECT_NAME"];
        }
        
    } else {    // 巡检项ID不存在
        NSString *iuiSql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE ID = '%@'", itemID];
        FMResultSet *iuiResult = [db executeQuery:iuiSql];
        while ([iuiResult next]) {
            itemName = [iuiResult stringForColumn:@"INSPECT_ADDTIONAL_NAME"];
        }
    }
    [db close];
    return itemName;
}

// 查找本条巡检项的状态
- (NSString *)getInspectItemStateByUserItemID:(NSString *)userItemID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE ID = '%@'", userItemID];
    FMResultSet *result = [db executeQuery:sql];
    
    NSString *state;
    while ([result next]) {
        state = [result stringForColumn:@"INSPECT_CURRENT_STATE"];
    }
    [db close];
    return state;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end




